import { AddInvoice, EditInvoice } from '../../../../services/order/orderConfirm';
import Toast from 'tdesign-miniprogram/toast/index';
import util from "../../../../utils/util.js"

Page({
  orderNo: '',
  data: {
    invoiceState: { invoiceTitle: '', "invoiceType": 1, isDefault: 0 },
  },
  onLoad(options) {
    if (options.invoiceState) {
      let invoiceState = JSON.parse(options.invoiceState);
      invoiceState.isDefault = invoiceState.isDefault === 1 ? true : false;
      invoiceState.accountInvoiceId = invoiceState.id;
      this.setData({ invoiceState })
    }
  },

  onInputValue(e) {
    const { value } = e.detail;
    const { type } = e.currentTarget.dataset;
    this.setData({ [`invoiceState.${type}`]: value })
  },

  /* 提交 */
  onSure() {
    const { invoiceState } = this.data
    if (!invoiceState.invoiceTitle) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请填写发票抬头',
      });
      return;
    }
    invoiceState.isDefault = invoiceState.isDefault === true ? 1 : 0
    if (invoiceState.id) {
      EditInvoice(invoiceState).then(res => {
        if (res.code == '0000') {
          util.showToast("编辑成功", "none", 600)
          setTimeout(() => {
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2]; //上一页
            prevPage.setData({ refresh: true });
            wx.navigateBack({ delta: 1 });
          }, 600);
        }
      })
    } else {
      AddInvoice(invoiceState).then(res => {
        if (res.code == '0000') {
          util.showToast("添加成功", "none", 600)
          setTimeout(() => {
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2]; //上一页
            prevPage.setData({ refresh: true });
            wx.navigateBack({ delta: 1 });
          }, 600);
        }
      })
    }
  }
});
